"""
题目：返回双链表的最后一个节点（空链表返回 None）。
"""


class Node:
    def __init__(self, val=0, prev=None, next=None):
        self.val = val
        self.prev = prev
        self.next = next


def get_tail(head):
    """获取双链表的尾节点"""
    if head is None:
        return None
    current = head
    # 遍历到最后一个节点（next为None）
    while current.next:
        current = current.next
    return current


def create_doubly_linked_list(arr):
    if not arr:
        return None
    head = Node(arr[0])
    current = head
    for val in arr[1:]:
        new_node = Node(val)
        current.next = new_node
        new_node.prev = current
        current = new_node
    return head


# 测试
if __name__ == "__main__":
    # 非空链表
    head = create_doubly_linked_list([1, 2, 3, 4])
    tail = get_tail(head)
    print(tail.val if tail else None)  # 输出: 4

    # 单节点链表
    single_head = create_doubly_linked_list([5])
    single_tail = get_tail(single_head)
    print(single_tail.val if single_tail else None)  # 输出: 5

    # 空链表
    empty_head = create_doubly_linked_list([])
    empty_tail = get_tail(empty_head)
    print(empty_tail.val if empty_tail else None)  # 输出: None